package isv

import (
    "strconv"
	"time"
	//"strings"
    "dhfshop/models/isv"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"wxsdk/oauth"
	"github.com/pkg/errors"
)

//证书授权
type IsvAuthrizeController struct {
	base.BaseController
}

func (this *IsvAuthrizeController) GetPreAuthCode() {
    isvAppId := beego.AppConfig.String("IsvAppID")
	authorize, err := isv.GetAuthorizeByAppId(isvAppId)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	preAuthCode, expiresIn, err := oauth.GetPreAuthCode(isvAppId,authorize.AccessToken)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	this.Data["json"] = map[string]string{
	    "pre_auth_code": preAuthCode,
		"expires_in": strconv.FormatInt(expiresIn, 10),
	}
	this.ServeJSON()
}

func (this *IsvAuthrizeController) GetApiQueryAuth() {
    companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := struct {
	    PartnerId          int64     `form:"partner_id" valid:"Required"`
		StoreId            int64     `form:"store_id" valid:"Required"`
		AuthorizationCode  string  `form:"authorization_code" valid:"Required"`
	}{PartnerId: companyId}  
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	isvAppId := beego.AppConfig.String("IsvAppID")
	authorize, err := isv.GetAuthorizeByAppId(isvAppId)
	if err != nil {
	    err = errors.Wrap(err, "GetAuthorizeByAppId... ")
		this.ServeError(err.Error())
		return
	}
	rsp, err := oauth.ApiQueryAuth(isvAppId,authorize.AccessToken,v.AuthorizationCode)
	if err != nil {
	    err = errors.Wrap(err, "ApiQueryAuth... ")
		this.ServeError(err.Error())
		return
	}
	curTime := time.Now().Unix()
	id, err := isv.SaveCustTokenByAppId(rsp.AuthorizationInfo.AuthorizerAppid,rsp.AuthorizationInfo.AccessToken,
	                                    rsp.AuthorizationInfo.RefreshToken,curTime+int64(rsp.AuthorizationInfo.ExpiresIn),
										v.PartnerId,v.StoreId)
	if err != nil {
	    err = errors.Wrap(err, "SaveCustTokenByAppId... ")
		this.ServeError(err.Error())
		return
	}
	/*
	putParams := &beanstalk.PutParams{1024, 6600*time.Second, 60*time.Second}  //Priority,Delay,TTR
	if id, err := beanstalkcli.BeansTalkPool.Put(gearQueue, curJson, putParams); err != nil {
		beego.Debug("id:", id, "err:", err.Error())
	}
	*/
	userInfo, err := oauth.GetAuthorizerInfo(isvAppId,authorize.AccessToken,rsp.AuthorizationInfo.AuthorizerAppid)
	if err != nil {
	    err = errors.Wrap(err, "GetAuthorizerInfo: ")
		this.ServeError(err.Error())
		return
	}
	custAccount, err := isv.AuthorizerInfoCustAccount(&userInfo)
	fields := []string{"NickName","AvartarUrl","ServiceTypeId","VerifyTypeId","PrincipalName","Alias",
	                   "OpenStore","OpenScan","OpenPay","OpenCard","OpenShake","QrcodeUrl","FuncIds","Status"}
	
	id, err = isv.UpdateCustAccountByAppId(custAccount, fields...)
	if err != nil {
	    err = errors.Wrap(err, "UpdateCustAccountByAppId: ")
		this.ServeError(err.Error())
		return
	}
	this.Data["json"] = map[string]string{
	    "cust_account_id": strconv.FormatInt(id, 10),
	}
	this.ServeJSON()
}

func (this *IsvAuthrizeController) CtrlGetAuthorizerInfo() {
    var (
	    custAccounts  []*isv.CustAccount
		err           error
	)
	companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	offset := 0     //default is 0
	limit := 50    //default is 50
	v := struct {
	    PageSize  int     `form:"page_size"`
		PageNo    int     `form:"page_no"`
		StoreId   int64   `form:"store_id"`
	}{PageSize:50, PageNo:1}     
	this.ParseForm(&v)
	v.PageNo = v.PageNo - 1     //为了计算offset
	offset = v.PageNo*v.PageSize
	limit = v.PageSize
	if v.StoreId > 0 {
	    custAccounts, err = isv.QueryCustAccountsByStoreId(v.StoreId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}else{
	    custAccounts, err = isv.QueryCustAccountsByPartnerId(companyId, offset, limit)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	this.Data["json"] = custAccounts
	this.ServeJSON()
}
